package itbour.onetouchshow.activity.video.videopreview;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.andview.adapter.BaseRecyclerHolder;
import com.google.gson.Gson;
import com.lsjr.utils.NetUtils;
import com.utils.permission.Permission;
import com.xiao.nicevideoplayer.LogUtil;
import com.xiao.nicevideoplayer.NiceVideoPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.version1_2.CommoninchingVideoBgActivity;
import itbour.onetouchshow.activity.version1_6.MakeActivityV1_6;
import itbour.onetouchshow.activity.web.CommWebActivity;
import itbour.onetouchshow.activity.web.CreateOrderActivity;
import itbour.onetouchshow.base.BaseIJKPlayActivity;
import itbour.onetouchshow.base.BaseRefreshAdapter;
import itbour.onetouchshow.base.IntentCode;
import itbour.onetouchshow.bean.LoadVideoUserDocBg;
import itbour.onetouchshow.bean.VideoBean;
import itbour.onetouchshow.bean.VideoPreviewBean;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.listener.PermissionListener;
import itbour.onetouchshow.utils.BroadcastAction;
import itbour.onetouchshow.utils.FinshBroadcast;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.OnMultiClickUtils;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.widget.BgSelectorWindow;
import itbour.onetouchshow.widget.ShareDialogFragment;
import itbour.onetouchshow.widget.circlemenu.AnnularMenu;
import itbour.onetouchshow.widget.circlemenu.ShadowImageView;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */
@SuppressLint("ValidFragment")
public class VideoPreviewActivity extends BaseIJKPlayActivity<VideoPreviewContract.View, VideoPreviewPresenter> implements VideoPreviewContract.View {
    @BindView(R.id.id_rv_vb)
    protected RecyclerView idRvVb;

    @BindView(R.id.detail_player)
    protected NiceVideoPlayer customVideoPlay;
    @BindView(R.id.id_ry_recommended)
    protected LinearLayout ryRecommended;
    @BindView(R.id.id_ly_form)
    protected LinearLayout showLyForm;  //表单内容
    @BindView(R.id.id_video_ry)
    protected RelativeLayout idVideoRy;
    @BindView(R.id.nest_soroll)
    protected ScrollView scrollView;
    @BindView(R.id.menu)
    protected AnnularMenu menu;
    /*首先隐藏  只有数据出来了才显示*/
    @BindView(R.id.id_scorll_root)
    protected RelativeLayout contentLayout;
    //底部导航操作
    @BindView(R.id.id_user_make)
    protected LinearLayout idLyuserMake;
    protected int mbgColumn;
    /*视频数据*/
    protected VideoBean videoBean;
    /*作品预览*/
    // VideoPreviewFragment videoPreviewFragment;
    /*作品核心数据*/
    protected VideoPreviewBean videoPreviewBean;
    /*背景数据*/
    protected VideoPreviewBean.BgInfoBean bgInfo;
    /*背景列表*/
    protected List<VideoPreviewBean.BgInfoBean.ListBean> mbgData;
    protected BgSelectorWindow bgSelectorWindow;
    /*视频位置*/
    protected VideoPreviewBean.BgInfoBean.CurrentBgBean.VideoFrameBean videoFrame;
    protected String bgUrl;
    protected String subType;
    @BindView(R.id.id_prv_bg)
    protected ImageView idPrvBg;
    protected VideoBgViewpagerAdapter viewpagerAdapter;
    protected String docId = null;
    @BindView(R.id.id_ry_down)
    LinearLayout idRyDown;
    @BindView(R.id.id_ry_share)
    LinearLayout idRyShare;
    @BindView(R.id.fragment_content)
    FrameLayout fragmentContent;
    @BindView(R.id.id_tv_show_more)
    TextView tvShowMore;
    @BindView(R.id.id_root_ry)
    RelativeLayout id_root_ry;
    @BindView(R.id.id_tv_gotoremovewater)
    TextView geToRemoveWater;
    //表格反馈入口
    @BindView(R.id.id_free_back_form)
    RelativeLayout freeBackForm;
    @BindView(R.id.id_open_form)
    RelativeLayout openFrom;
    @BindView(R.id.tv_open_form_staus)
    TextView tvOpenfromStaus;  //表单内容
    @BindView(R.id.menu_item1)
    ShadowImageView menuItem1;
    @BindView(R.id.menu_item2)
    ShadowImageView menuItem2;
    @BindView(R.id.menu_item3)
    ShadowImageView menuItem3;
    @BindView(R.id.rl_stub)
    RelativeLayout rlStub;
    /*用户操作类型*/
    UserMakeTag userMakeTag = UserMakeTag.MAKE;
    private int count;
    //这是用于退出三段式逻辑的广播
    private FinshBroadcast quitThreeLogicBroadcast = new FinshBroadcast();

    @Override
    public void loadSucceed(String result) {

    }

    public UserMakeTag getState() {
        return userMakeTag;
    }

    public void setState(UserMakeTag state) {
        this.userMakeTag = state;
    }

    @Override
    public int getFragmentContentId() {
        return R.id.fragment_content;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        //setTitleText("作品预览");
        getToolBarView().setRightText("完成").getRightTextView().setVisibility(View.VISIBLE);
//        getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                sendRemoveThreeLogic();
//            }
//        });
//        if (subType != null) {
//            if (subType.equals(WorkPlatform.W0RK)) {
//                //个任务中心跳转逻辑
//                getToolBarView().setRightText("修改作品").getRightTextView().setVisibility(View.VISIBLE);
//                getToolBarView().getRightTextView().setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        if (videoPreviewBean.getWatermark() == 1) {
//                            mPresenter.getDocString(videoPreviewBean.getId() + "");
//                        } else {
//                            //如果已经去水印  重新拷贝生成
//                            mPresenter.getCopyDocStringAndNew(videoPreviewBean.getId() + "");
//                        }
//                    }
//                });
//            }
//        }
//        getToolBarView().getLeftimageView().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                jugleQuit();
//            }
//        });

    }

    protected void jugleQuit() {
        if (videoPreviewBean == null || videoPreviewBean.getWatermark() == 1) {
            finish();
        } else {
            sendRemoveThreeLogic();
        }
    }

    @Override
    public void onBackPressed() {
        if (onBackPressd()) {
            return;
        }
        jugleQuit();
    }

    @Override
    public void loadFaild(String error) {
        dismissProgressDialog();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_videopreview;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        // mPresenter.loadPreviewBg();
        //避免键盘弹出底部按钮弹起
        getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        Bundle extras = getIntent().getExtras();

        if (extras != null) {
            docId = extras.getString(AppConst.DOCID);
            subType = extras.getString(WorkPlatform.TYPE);
        }
        if (subType != null) {
            if (subType.equals(WorkPlatform.W0RK)) {
                //作品进来不显示背景推荐
                ryRecommended.setVisibility(View.GONE);
                menu.setVisibility(View.GONE);
            }
        }


        super.afterCreate(savedInstanceState);
        mPresenter = new VideoPreviewPresenter(this);
        EventBus.getDefault().register(this);
        registerExitReceiver();


        //  UserMakeTag.MAKE

        showProgressDialogWithText("加载中...");
        initTitle();
        initCircleMenu();
        mPresenter.loadDocPreview(docId);
        mbgData = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        idRvVb.setLayoutManager(linearLayoutManager);
        viewpagerAdapter = new VideoBgViewpagerAdapter(getApplicationContext(), mbgData, R.layout.item_video_pg_bg);
        idRvVb.setAdapter(viewpagerAdapter);
    }

    @Override
    protected boolean isLoopPlay() {
        return !(subType == null || subType.equals(WorkPlatform.W0RK));
    }

    @Override
    protected NiceVideoPlayer getmNiceVideoPlayer() {
        return customVideoPlay;
    }

    @Override
    protected int videoHeight() {
        return UIUtils.getHForScan(videoBean.getW(), videoBean.getH());
    }

    private void initCircleMenu() {
        rlStub.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //如果在三个展开的区域内 不消耗该事件
                float x = event.getRawX();
                float y = event.getRawY();
                int[] item1Pos = {0, 0};
                int[] item2Pos = {0, 0};
                int[] item3Pos = {0, 0};
                menuItem1.getLocationOnScreen(item1Pos);
                menuItem2.getLocationOnScreen(item2Pos);
                menuItem3.getLocationOnScreen(item3Pos);

                RectF item1RF = new RectF(item1Pos[0], item1Pos[1], item1Pos[0] + UIUtils.dp2px(60), item1Pos[1] + UIUtils.dp2px(60));
                RectF item2RF = new RectF(item2Pos[0], item2Pos[1], item2Pos[0] + UIUtils.dp2px(60), item2Pos[1] + UIUtils.dp2px(60));
                RectF item3RF = new RectF(item3Pos[0], item3Pos[1], item3Pos[0] + UIUtils.dp2px(60), item3Pos[1] + UIUtils.dp2px(60));

                boolean bol = false;


                if (item1RF.contains(x, y)) {
                    L_.i("item1RF.contains(x,y)");
                } else if (item2RF.contains(x, y)) {
                    L_.i("item2RF.contains(x,y)");
                } else if (item3RF.contains(x, y)) {
                    L_.i("item3RF.contains(x,y)");
                } else {
                    L_.i("menu.toggle()");
                    bol = true;
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        menu.toggle();
                    }
                }
                L_.i("bol===" + bol);
                return bol;

            }
        });


        menu.setOnMenuItemClickListener(new AnnularMenu.OnMenuItemClickListener()

        {
            @Override
            public void onClick(View view, int position) {
                switch (position) {
                    case 1:
                        if (OnMultiClickUtils.isFastClick()) {
                            showBgDialog();
                        }
                        break;
                    case 2:
                        mPresenter.deleteVideoBg(videoPreviewBean.getId() + "");
                        break;
                    case 3:
                        //跳转到公共微调界面

                        Intent intent = new Intent(VideoPreviewActivity.this, CommoninchingVideoBgActivity.class);
                        //  DesignListBean.ListBean listBean = pagerAdapter.getCurrentFragment().listBean;
                        int id = videoPreviewBean.getId();
                        L_.e(videoPreviewBean.getId() + "作品ID");
                        intent.putExtra(IntentCode.INCHING_TYPE, IntentCode.SUB_TYPE_PRODUCE);
                        intent.putExtra(IntentCode.TAG, IntentCode.INTENT_VERTICAL_VIDEP);
                        intent.putExtra(AppConst.DOCID, id);
                        intent.putExtra(AppConst.BGID, id);
                        intent.putExtra(WorkPlatform.TYPE, subType);
                        //bundle.putString(WorkPlatform.TYPE, subType);
                        startActivity(intent);
                        //startActivityForResult(intent,70000);
                        break;
                }

                if (menu.isOpen()) {
                    menu.toggle();
                }
            }

            @Override
            public void onMenuOpen() {

                if (rlStub != null && rlStub.getVisibility() != View.VISIBLE) {

                    rlStub.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onMenuClose() {
                if (rlStub != null && rlStub.getVisibility() != View.GONE) {

                    rlStub.setVisibility(View.GONE);
                }
            }
        });
    }

    //protected ComplexDialogFrag complexDialogFrag;

    public void setFormStaus() {
        if (videoPreviewBean.getFormState() == 0) {
            tvOpenfromStaus.setText("未开启");
        } else {
            tvOpenfromStaus.setText("已开启");
        }
        if (videoPreviewBean.getShowFormFb() == 0) {
            freeBackForm.setVisibility(View.GONE);
        } else {
            freeBackForm.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.id_ry_down,
            R.id.id_ry_share,
            R.id.id_tv_show_more,
            R.id.id_tv_gotoremovewater,
            R.id.id_free_back_form,
            R.id.id_open_form})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.id_ry_down:
                requestPermission(new PermissionListener() {
                    @Override
                    public void onGranted() {
                        // T_.showToastReal("成功");
                        showProgressDialogWithText("正在下载...");
                        mPresenter.getDownVideoUrl(videoPreviewBean.getId() + "");
                    }

                    @Override
                    public void onDenied(List<String> list) {
                        //T_.showToastReal("拒绝");
                    }
                }, Permission.Group.STORAGE);

                // requestPermissions();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                }
                break;
            case R.id.id_ry_share:
                String docNm = videoPreviewBean.getDocNm();
                L_.i(docNm);

                // ShareDialogFragment.getInstance().onShow(VideoPreviewActivity.this);
                ShareDialogFragment.getInstance().setBuilder(new ShareDialogFragment.Builder()
//                        /*setContext(videoPreviewBean.getBgInfo().getCurrentBg().getDocNm())*/
                        // .setTitle(videoPreviewBean.g)
                        .setDocId(videoPreviewBean.getId() + "").setTitle(docNm)
                        .setAvUrl(videoPreviewBean.getVideo().getThumbs().get(0)).setmType(5)).onShow(VideoPreviewActivity.this);
                break;
            case R.id.id_tv_show_more:
                //更多背景
                //mPresenter.loadVideoUserDocBg(videoPreviewBean.getId() + "");
                if (OnMultiClickUtils.isFastClick()) {
                    if (NetUtils.isConnected(getApplication())) {
                        showBgDialog();
                    } else {
                        T_.showCustomToast("请检查网络");
                    }
                }
                break;
            case R.id.id_tv_gotoremovewater:
                //T_.showToastReal("去水印作品ID" + videoPreviewBean.getId());
                //mPresenter.creatToWatermark(videoPreviewBean.getId() + "");
                if (NetUtils.isConnected(getApplication())) {
                    if (videoPreviewBean.getWatermark() == 1 && videoPreviewBean.getWatermarkPay() == 1) {
                        showProgressDialogWithText("正在努力去水印");
                        mPresenter.removeWatermark(videoPreviewBean.getId() + "");
                    } else {
                        showRemoveWaterDialog();

                    }
                } else {
                    T_.showCustomToast("请检查网络");
                }

                //创建去水印
                break;
            case R.id.id_free_back_form:
                if (NetUtils.isConnected(getApplication())) {
                    //用户反馈
                    bundle.putString(AppConst.WEBTYPE, AppConst.TYPE_FREEBACKINFO);
                    bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
                    openActivity(CommWebActivity.class, bundle);
                } else {
                    T_.showCustomToast("请检查网络");
                }

                break;
            case R.id.id_open_form:
                if (NetUtils.isConnected(getApplication())) {
                    //添加表格
                    bundle.putString(AppConst.WEBTYPE, AppConst.TYPE_ADDFORM);
                    bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
                    Intent intent = new Intent(VideoPreviewActivity.this, CommWebActivity.class);
                    //  openActivity(CommWebActivity.class, bundle);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 200);
                } else {
                    T_.showCustomToast("请检查网络");
                }
                break;
        }
    }

    @SuppressLint("ValidFragment")
    public void showRemoveWaterDialog() {


        new OneToucDialog.Builder(this)
                .content("去水印后,修改作品将生成带水印新作品，" +
                        "去水印作品仍会保留")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Bundle bundle = new Bundle();
                bundle.putString("docId", videoPreviewBean.getId() + "");
                openActivity(CreateOrderActivity.class, bundle);
            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();


//        complexDialogFrag = new ComplexDialogFrag() {
//            @Override
//            public Builder setBuilder() {
//                return new Builder().setTitle(" ")
//                        .setCancletext("取消").setCancleListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View view) {
//                                complexDialogFrag.dismiss();
//                            }
//                        })
//                        .setConfirmText("确定").setConfirmListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                complexDialogFrag.dismiss();
//                                Bundle bundle = new Bundle();
//                                bundle.putString("docId", videoPreviewBean.getId() + "");
//                                openActivity(CreateOrderActivity.class, bundle);
//                            }
//                        }).setContext("去水印后,修改作品将生成带水印新作品，" +
//                                "去水印作品仍会保留").setPlatform(DialogPlatform.TWO_BTN);
//            }
//        };
//        complexDialogFrag.show(getFragmentManager().beginTransaction(), null);

    }

    @Override
    protected void onResume() {
        isallowPlay = !(bgSelectorWindow != null && bgSelectorWindow.isShowing());
        super.onResume();

    }

    public void showBgDialog() {
        //  getOneTouchVideoPlayLayout().getLayoutVideo().onVideoPause();
        getmNiceVideoPlayer().pause();
        bgSelectorWindow = new BgSelectorWindow(getApplication(), videoPreviewBean.getId() + "", new BgSelectorWindow.ItemSelectListener() {
            @Override
            public void onSelect(LoadVideoUserDocBg.ListBean listBean) {
                VideoPreviewBean.BgInfoBean.ListBean bgBean = new VideoPreviewBean.BgInfoBean.ListBean();
                bgBean.setId(listBean.getId());
                bgBean.setThumb(listBean.getThumb());
                showProgressDialogWithText("正在设置背景");
                setState(UserMakeTag.SETBG);
                mPresenter.loadSetVideoBg(videoPreviewBean.getId() + "", bgBean.getId() + "");
            }
        });
        bgSelectorWindow.showAtLocation(id_root_ry, Gravity.TOP, 0, 0);
    }

    /**
     * 点击背景选择之后也是此操作
     * <p>
     * 点击切换背景先设置背景
     * <p>
     * 在获取作品预览
     * <p>
     * 设置背景后重新获取预览数据
     */
    @Override
    public void loadDocPreviewSuccess(String result) {
        L_.e(result);
        dismissProgressDialog();

        videoPreviewBean = new Gson().fromJson(result, VideoPreviewBean.class);
        bgInfo = videoPreviewBean.getBgInfo();
        mbgColumn = bgInfo.getColumn();
        mbgData = bgInfo.getList();
        videoBean = videoPreviewBean.getVideo();
        //L_.e(videoBean.toString());
        // geToRemoveWater.setEnabled(true);
        // geToRemoveWater.setText(videoPreviewBean.getWatermarkFee() / 100 + getResources().getString(R.string.gotowaterprice));
        viewpagerAdapter.notifyDataSetChanged(mbgData);

        //没有背景的
        if (bgInfo.getCurrentBg() != null) {
            videoFrame = bgInfo.getCurrentBg().getVideoFrame();
            bgUrl = bgInfo.getCurrentBg().getImage().getThumbs().get(0);
            if (videoFrame != null) {
                showRealSizeView();
            }
            ryRecommended.setVisibility(View.GONE);
            menu.setVisibility(View.VISIBLE);
        } else {
            bgUrl = null;
            cleanBg();
            menu.setVisibility(View.GONE);
            ryRecommended.setVisibility(View.VISIBLE);
        }
        if (subType != null) {
            if (subType.equals(WorkPlatform.W0RK)) {
                //作品进来不需要要背景
                ryRecommended.setVisibility(View.GONE);
                menu.setVisibility(View.GONE);
            }
        }

        setFormStaus();
        waterStatus();
        idLyuserMake.setVisibility(View.GONE);
        contentLayout.setVisibility(View.VISIBLE);
        //getOneTouchVideoPlayLayout().getLayoutVideo().setUp(videoPreviewBean.getVideo().getVideoUrl(), false, videoPreviewBean.getDocNm());
        // this.videoBean = videoPreviewBean.getVideo();
        // initVideoPaly(videoPreviewBean.getVideo().getVideoUrl(), videoPreviewBean.getDocNm());
        if (!isPause) {
            //  initVideoPaly(videoPreviewBean.getVideo().getVideoUrl(), videoPreviewBean.getDocNm());
            LogUtil.i("mUrl   loadDocPreviewSuccess--------------" + videoPreviewBean.getVideo().getVideoUrl());
            customVideoPlay.setUp(videoPreviewBean.getVideo().getVideoUrl(), null);
        }

//        Bundle bundle = new Bundle();
//        // bundle.putString("bgString", result);
//        bundle.putString(AppConst.DOCID, videoPreviewBean.getId() + "");
//        bundle.putString(WorkPlatform.TYPE, WorkPlatform.MOUDLE);
//        openActivity(VideoBgEditActivity.class, bundle);
//        this.finish();

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return true;
    }

    @Override
    public void loadNewDocPreviewSuccess(String result) {

    }

    public void showRealSizeView() {
        VideoPreviewBean.BgInfoBean.CurrentBgBean.ImageBean image = videoPreviewBean.getBgInfo().getCurrentBg().getImage();
        int w = (int) image.getW();
        int h = (int) image.getH();
        int x = (int) videoFrame.getX();
        int y = (int) Math.ceil(videoFrame.getY());
        int videoH = (int) videoFrame.getH();
        int[] whd = UIUtils.WHD();
        int visableW = whd[0];
        float scale = w * 1.0f / visableW;

        RelativeLayout.LayoutParams imgLp = (RelativeLayout.LayoutParams) idPrvBg.getLayoutParams();
        h = (int) (visableW * h * 1.0f / w);
        imgLp.width = visableW;
        imgLp.height = h;
        idPrvBg.setLayoutParams(imgLp);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        y = (int) Math.ceil(y * 1.0f / scale);
        x = (int) Math.ceil(x * 1.0f / scale);
        videoH = (int) (videoH * 1.0f / scale);
        lp.leftMargin = x;
        lp.topMargin = y;
        lp.height = videoH;
        int videoW = (int) (videoFrame.getW() * 1.0f / scale);
        lp.width = videoW;
        idVideoRy.setLayoutParams(lp);
        L_.e(bgUrl);
        if (!TextUtils.isEmpty(bgUrl)) {
            ImageLoader.getInstance().showImageNoplace(VideoPreviewActivity.this, bgUrl, idPrvBg);
        }
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) showLyForm.getLayoutParams();
        //layoutParams.addRule(idPrvBg,);
        layoutParams.addRule(RelativeLayout.BELOW, R.id.id_prv_ry);// 子控件相对于控件：imageViewId在其的下面
        showLyForm.setLayoutParams(layoutParams);


        //int videoW = (int) videoFrame.getW();
        // float scaleVideo = videoW * 1.0f / visableW;
        //  int videoWidth = (int) (videoFrame.getW() * scaleVideo);
        // int videoHeight = (int) (videoFrame.getH() * scaleVideo);
        videoW = (int) (videoW * 1.0f / scale);
        //setVideoHight(videoW, videoH);


    }

    public void setVideoLayout() {

        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        lp.leftMargin = 0;
        lp.topMargin = 0;
        int videoH = (int) videoFrame.getH();
        lp.height = videoH;
        idVideoRy.setLayoutParams(lp);

    }

    /*没有背景*/
    protected void cleanBg() {
        idPrvBg.setImageResource(0);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) idVideoRy.getLayoutParams();
        lp.leftMargin = 0;
        lp.topMargin = UIUtils.dip2px(15);
        lp.bottomMargin = UIUtils.dip2px(10);
        // int videoH = videoFrame.getH();
        //ViewGroup.LayoutParams layoutParams1 = customVideoPlay.getLayoutVideo().getLayoutParams();
        // layoutParams1.height=UIUtils.WH()[0]*videoBean.getH()/videoBean.getW();
        // lp.height = videoHeight();
        lp.width = UIUtils.WH()[0];
        // customVideoPlay.setLayoutParams(layoutParams1);
        idVideoRy.setLayoutParams(lp);

        RelativeLayout.LayoutParams imgLp = (RelativeLayout.LayoutParams) idPrvBg.getLayoutParams();
        imgLp.width = FrameLayout.LayoutParams.MATCH_PARENT;
        imgLp.height = FrameLayout.LayoutParams.MATCH_PARENT;
        idPrvBg.setLayoutParams(imgLp);

        //layoutParams.addRule(RelativeLayout.BELOW ,R.id.id_prv_bg)
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) showLyForm.getLayoutParams();
        //layoutParams.addRule(idPrvBg,);
        layoutParams.addRule(RelativeLayout.BELOW, R.id.id_video_ry);// 子控件相对于控件：imageViewId在其的下面
        showLyForm.setLayoutParams(layoutParams);


        scrollView.scrollTo(0, 0);
    }

    @Override
    public void loadVideoUserDocBgSucceed(String result) {

    }

    /*去水印完成*/
    @Override
    public void removeWaterLoadDocPreview(String result) {
        dismissProgressDialog();
        videoPreviewBean = new Gson().fromJson(result, VideoPreviewBean.class);
        if (bgSelectorWindow != null) {
            bgSelectorWindow.dismiss();
        }
        //initVideoPaly(videoPreviewBean.getVideo().getVideoUrl(), videoPreviewBean.getDocNm());
        LogUtil.i("mUrl   removeWaterLoadDocPreview--------------" + videoPreviewBean.getVideo().getVideoUrl());
        // customVideoPlay.setUp(videoPreviewBean.getVideo().getVideoUrl(), null);
        //customVideoPlay.releasePlayer();
        //customVideoPlay.setUp(videoPreviewBean.getVideo().getVideoUrl(), null);
        onChageUrlStartPlay(videoPreviewBean.getVideo().getVideoUrl(), videoPreviewBean.getDocNm());
        // customVideoPlay.start(currentPosition);
        L_.e("re" + result);
        waterStatus();
    }

    /**
     * 去水印状态
     */
    public void waterStatus() {
        if (videoPreviewBean == null) return;
        switch (videoPreviewBean.getWatermark()) {
            case 1:
                //已付款
                switch (videoPreviewBean.getWatermarkPay()) {
                    case 1:
                        //有水印 重新发起去水印
                        geToRemoveWater.setEnabled(true);
                        geToRemoveWater.setText("去水印(已支付)");
                        //mPresenter.removeWatermark(videoPreviewBean.getId() + "");
                        break;
                    case 0:
                        geToRemoveWater.setEnabled(true);
                        geToRemoveWater.setText(videoPreviewBean.getWatermarkFee() / 100 + getResources().getString(R.string.gotowaterprice));
                        break;
                }
                break;
            case 0:
                geToRemoveWater.setText("已去水印");
                geToRemoveWater.setEnabled(false);
                ryRecommended.setVisibility(View.GONE);
                // idRvVb.setVisibility(View.GONE);
                break;
        }

    }

    @Override
    public void createWaterOrderSuccess(String result) {
        dismissProgressDialog();
        try {
            JSONObject jsonObject = JSON.parseObject(result);
            // order no  61R45L09X95P6
            String orderid = jsonObject.getString("orderId");
            String orderNo = jsonObject.getString("orderNo");
            L_.e("orderid  :" + orderid + "----orderNo ：" + orderNo);
            Bundle bundle = new Bundle();
            bundle.putString("docId", orderid + "");
            openActivity(CreateOrderActivity.class, bundle);
            //onOrderPay(orderid);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showFromStaus(String result) {
        videoPreviewBean = new Gson().fromJson(result, VideoPreviewBean.class);
        setFormStaus();
    }

    @Override
    public void deleteVideoBgSuccess(String result) {
//        if (fragmentContent.getVisibility() == View.VISIBLE) {
//            videoPreviewFragment = null;
//            fragmentContent.setVisibility(View.GONE);
//        }
        //startPlayVideo();
        mPresenter.loadDocPreview(videoPreviewBean.getId() + "");
        // initVideoPaly(videoPreviewBean.getVideo().getVideoUrl(), videoPreviewBean.getDocNm());
        customVideoPlay.setUp(videoPreviewBean.getVideo().getVideoUrl(), null);
        LogUtil.i("mUrl   deleteVideoBgSuccess--------------" + videoPreviewBean.getVideo().getVideoUrl());
    }

    @Override
    public void downLoadVideoSuccess(String string) {
        dismissProgressDialog();

//        complexDialogFrag = new ComplexDialogFrag() {
//            @Override
//            public Builder setBuilder() {
//                return new Builder().setTitle(" ")
//                        .setConfirmText("确定").setConfirmListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                complexDialogFrag.dismiss();
//                            }
//                        }).setContext("已成功下载到本地").setPlatform(DialogPlatform.ONE_BTN);
//            }
//        };
//        complexDialogFrag.show(getFragmentManager().beginTransaction(), null);


        OneToucDialog show = new OneToucDialog.Builder(this)
                .content("已成功下载到本地")
                .positiveText("确定").onPositive(new OneToucDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(OneToucDialog dialog, DialogAction which) {
                        Log.e("TAH", "点击确定");
                    }
                }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();

    }

    @Override
    public void copyAndNewProductSuccess(String result) {
        L_.e("copyAndNewProductSuccess MakeActivityV1_6" + (count++));
        Bundle bundle = new Bundle();
        bundle.putString("module", result);
        bundle.putString(WorkPlatform.TYPE, WorkPlatform.MOUDLE);
        openActivity(MakeActivityV1_6.class, bundle);
    }

    @Override
    public void getDocStringPreview(String result) {
        L_.e("getDocStringPreview MakeActivityV1_6" + (count++));
        Bundle bundle = new Bundle();
        bundle.putString("module", result);
        bundle.putString(WorkPlatform.TYPE, WorkPlatform.W0RK);
        openActivity(MakeActivityV1_6.class, bundle);
    }

    @Override
    public void getDownloadUrl(String result) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

//    @Override
//    public CustomVideoPlay getOneTouchVideoPlayLayout() {
//        return customVideoPlay;
//    }


    /**
     * threadMode 执行的线程方式
     * priority 执行的优先级
     * sticky 粘性事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 50, sticky = true)
    public void paySuccess(Integer code) {
        //  L_.e("支付成功 去水印");
        // 如果有一个地方用 EventBus 发送一个 String 对象，那么这个方法就会被执行
        if (code == 1000) {
            geToRemoveWater.setText("去水印(已支付)");
            videoPreviewBean.setWatermarkPay(1);
            videoPreviewBean.setWatermark(1);
            showProgressDialogWithText("正在努力去水印");
            mPresenter.removeWatermark(videoPreviewBean.getId() + "");
        }
        if (code == 1200) {
            //视频背景修改后
            // isChangeBg = true;
            // getOneTouchVideoPlayLayout().getLayoutVideo().onVideoPause();
            showProgressDialogWithText("");
            // onPause();
            mPresenter.loadDocPreview(videoPreviewBean.getId() + "");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unRegisterExitReceiver();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 200) {
              /*获取作品预览 */
            //     mPresenter.showFromStaus(videoPreviewBean.getId() + "");
        }
    }

    //onCreate调用
    protected void registerExitReceiver() {
        IntentFilter exitFilter = new IntentFilter();
        exitFilter.addAction(BroadcastAction.EXIT_THREE_LOGIC);
        registerReceiver(quitThreeLogicBroadcast, exitFilter);
    }

    //onDestory反注册
    private void unRegisterExitReceiver() {

        unregisterReceiver(quitThreeLogicBroadcast);
    }

    protected void sendRemoveThreeLogic() {
        Intent intent = new Intent();
        intent.setAction(BroadcastAction.EXIT_THREE_LOGIC);
        sendBroadcast(intent);
    }

    public class VideoBgViewpagerAdapter extends BaseRefreshAdapter<VideoPreviewBean.BgInfoBean.ListBean> {

        public VideoBgViewpagerAdapter(Context context, List<VideoPreviewBean.BgInfoBean.ListBean> datas, int itemLayoutId) {
            super(context, datas, itemLayoutId);
        }

        @Override
        protected void convert(BaseRecyclerHolder var1, VideoPreviewBean.BgInfoBean.ListBean listBean, int var3) {
            ImageView imageView = var1.getView(R.id.id_vp_bg);
            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
            int width = UIUtils.WHD()[0] / mbgColumn - UIUtils.dp2px(15);
            int height = width * listBean.getH() / listBean.getW();
            String imUrl = ImageLoader.getShrinkImageUrl(listBean.getThumb(), width, height);
            layoutParams.width = width;
            layoutParams.height = height;
            ImageLoader.getInstance().showImageNoplace(VideoPreviewActivity.this, imUrl, imageView);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!NetUtils.isConnected(UIUtils.getContext())) {
                        T_.showCustomToast("请检查网络");
                        return;
                    }
                    showProgressDialogWithText("正在设置背景");
                    mPresenter.loadSetVideoBg(videoPreviewBean.getId() + "", listBean.getId() + "");
                }
            });
        }
    }
}
